package dice.sinanya.start;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.management.ManagementFactory;

public class SavePid {
    private static final Logger logger = LogManager.getLogger(SavePid.class.getName());

    public SavePid() {
    }

    public void savePid() {
        // get name representing the running Java virtual machine.
        String name = ManagementFactory.getRuntimeMXBean().getName();
        String pid = name.split("@")[0];
        try {
            File confFile = new File("./pid");
            writeFile(confFile.getPath(), pid);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 使用FileWriter类写文本文件
     */
    private void writeFile(String fileName, String text) throws IOException {
        try (FileWriter writer = new FileWriter(fileName, false)) {
            writer.write(text);
            return;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        throw new IOException("写入文件:\t" + fileName + "失败");
    }
}
